﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO.Pipes;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace cztOCR
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private const string UniqueMutexName = "cztBlue.cztOCR.UniqueMutex";
        private static Mutex _mutex;
        // 使用 Mutex和IPC实现的单实例，避免重复创建进程

        protected override void OnStartup(StartupEventArgs e)
        {
            bool isNewInstance;
            _mutex = new Mutex(true, UniqueMutexName, out isNewInstance);

            if (!isNewInstance)
            {
                // 通知已有实例激活窗口
                ActivateExistingInstance();
                // 关闭新实例
                Shutdown();
                return;
            }

            base.OnStartup(e);
        }

        private void ActivateExistingInstance()
        {
            // 使用进程间通信通知已有实例激活窗口
            // 这里可以使用多种IPC方法，下面是一个简单的示例
            using (var client = new NamedPipeClientStream(".", "cztOCR_Pipe", PipeDirection.Out))
            {
                try
                {
                    client.Connect(1000); // 1秒超时
                    using (var writer = new StreamWriter(client))
                    {
                        writer.WriteLine("activate");
                    }
                }
                catch
                {
                    // 处理连接失败的情况
                }
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            _mutex?.ReleaseMutex();
            _mutex?.Dispose();
            base.OnExit(e);
        }
    }
}
